package com.bishe.app.modules.usersalaryconfig.controller;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.bishe.app.core.api.CommonResult;
import com.bishe.app.core.api.CommonPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.app.core.enums.IsDel;
import com.bishe.app.core.utils.Lock;
import com.bishe.app.modules.groupuser.entity.GroupUser;
import com.bishe.app.modules.groupuser.service.GroupUserService;
import com.bishe.app.modules.user.entity.User;
import com.bishe.app.modules.user.service.UserService;
import com.bishe.app.modules.usersalaryconfig.model.UserSalaryInfo;
import com.bishe.app.modules.usersalaryconfig.model.UserSalarySearchDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bishe.app.modules.usersalaryconfig.service.UserSalaryConfigService;
import com.bishe.app.modules.usersalaryconfig.entity.UserSalaryConfig;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * <p>
 * 用户配置 前端控制器
 * </p>
 *
 * @author
 * @since 2024-03-13
 */
@RestController
@RequestMapping("/userSalaryConfig")
public class UserSalaryConfigController {

    @Autowired
    public UserSalaryConfigService userSalaryConfigService;

    @Resource
    private UserService userService;

    @Resource
    private GroupUserService groupUserService;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(rollbackFor = Throwable.class)
    @Lock(lockPrefix = "/userSalaryConfig",key = "#userSalaryConfig.userId", lockSecond = 60)
    public CommonResult create(@RequestBody UserSalaryConfig userSalaryConfig) {
        UserSalaryConfig userSalaryPresent = userSalaryConfigService.lambdaQuery()
                .eq(UserSalaryConfig::getUserId, userSalaryConfig.getUserId())
                .eq(UserSalaryConfig::getIsDel, IsDel.N.getCode())
                .one();
        if (Objects.nonNull(userSalaryPresent)) {
            userSalaryPresent.setConfigRule(userSalaryConfig.getConfigRule());
            userSalaryConfigService.updateById(userSalaryPresent);
        }else{
            userSalaryConfigService.save(userSalaryConfig);
        }
         return CommonResult.success(null);
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    @Lock(lockPrefix = "/userSalaryConfig",key = "#userSalaryConfig.userId", lockSecond = 60)
    public CommonResult update(@PathVariable Long id, @RequestBody UserSalaryConfig userSalaryConfig) {
        userSalaryConfig.setId(id);
        boolean success = userSalaryConfigService.updateById(userSalaryConfig);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
//    @Lock(lockPrefix = "/userSalaryConfig",key = "#userSalaryConfig.userId", lockSecond = 60)
    public CommonResult delete(@PathVariable Long id) {
        boolean success = userSalaryConfigService.removeById(id);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) {
        boolean success = userSalaryConfigService.removeByIds(ids);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/query/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<UserSalaryConfig> queryById(@PathVariable Long userId) {
        UserSalaryConfig userSalaryConfig = userSalaryConfigService.lambdaQuery()
                .eq(UserSalaryConfig::getUserId, userId)
                .eq(UserSalaryConfig::getIsDel, IsDel.N.getCode())
                .one();

        if (Objects.isNull(userSalaryConfig)) {
            return CommonResult.success(null);
        }
        return CommonResult.success(userSalaryConfig);
    }


    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<UserSalaryConfig>> listAll() {
        List<UserSalaryConfig> userSalaryConfigList = userSalaryConfigService.list();
        return CommonResult.success(userSalaryConfigList);
    }

    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<?>> page(@RequestBody UserSalarySearchDTO searchDTO) {
        Page<UserSalaryConfig> page = new Page(searchDTO.getPageNum(), searchDTO.getPageSize());
        List<GroupUser> groupUserList = new ArrayList<>();
        if (searchDTO.getGroupId() != null) {
            groupUserList = groupUserService.lambdaQuery()
                    .eq(GroupUser::getGroupId, searchDTO.getGroupId())
                    .eq(GroupUser::getIsDel, IsDel.N.getCode())
                    .list();
            if (CollectionUtils.isEmpty(groupUserList)) {
                return CommonResult.success(CommonPage.restPage(page));
            }
        }

        List<Long> userIds = groupUserList.stream().map(GroupUser::getUserId).collect(Collectors.toList());
        Page<User> userPage = new Page(searchDTO.getPageNum(), searchDTO.getPageSize());
        if (searchDTO.getUsername() != null) {
            userPage = userService.lambdaQuery()
                    .eq(User::getIsDel, IsDel.N.getCode())
                    .in(!CollectionUtils.isEmpty(userIds),User::getId, userIds)
                    .like(User::getName, searchDTO.getUsername())
                    .page(userPage);
        } else {
            userPage = userService.lambdaQuery()
                    .eq(User::getIsDel, IsDel.N.getCode())
                    .in(!CollectionUtils.isEmpty(userIds), User::getId, userIds)
                    .page(userPage);
        }

        // select user salary
        if (CollectionUtils.isEmpty(userPage.getRecords())) {
            return CommonResult.success(CommonPage.restPage(userPage));
        }

        Page<UserSalaryInfo> salaryInfoPage = new Page(searchDTO.getPageNum(), searchDTO.getPageSize(),userPage.getTotal());

        List<UserSalaryInfo> salaryInfoList = new ArrayList<>();
        for (User record : userPage.getRecords()) {
            UserSalaryConfig userSalaryConfig = userSalaryConfigService.lambdaQuery()
                    .eq(UserSalaryConfig::getUserId, record.getId())
                    .eq(UserSalaryConfig::getIsDel, IsDel.N.getCode())
                    .one();

            UserSalaryInfo usi = new UserSalaryInfo();
            if (Objects.nonNull(userSalaryConfig)) {
                BeanUtils.copyProperties(userSalaryConfig, usi);
            }
            record.setPwd("");
            usi.setUser(record);
            salaryInfoList.add(usi);
        }

        salaryInfoPage.setRecords(salaryInfoList);
        return CommonResult.success(CommonPage.restPage(salaryInfoPage));
    }


}



